package com.kl.service.ehcache;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

/**
 * 缓存处理SERVICE
 *
 * @author xr_zjb
 * @date 2017/06/02 13:55
 *
 */
@Service
public class EhcacheServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(EhcacheServiceImpl.class);

    @Autowired
    private EhCacheCacheManager cacheManager;

    /**
     * 新增缓存数据
     * @param cacheName 缓存名称
     * @param key 缓存key
     * @param data 缓存数据
     */
    public void putCache(String cacheName, Object key, Object data){
        if(StringUtils.isEmpty(cacheName) || key == null || data == null){
            logger.error("缓存处理SERVICE>>新增缓存数据>>请求数据有误");
            return;
        }
        synchronized(cacheName + "-" + key){
            Cache cache = cacheManager.getCache(cacheName);
            if(cache == null){
                logger.error("缓存处理SERVICE>>新增缓存数据>>发生错误：不存在缓存名称" + cacheName);
                return;
            }
            cache.put(key, data);
        }
    }

    /**
     * 删除缓存数据
     * @param cacheName 缓存名称
     * @param key 缓存数据KEY
     */
    public void delCache(String cacheName, Object key){
        if(StringUtils.isEmpty(cacheName) || key == null){
            logger.error("缓存处理SERVICE>>删除缓存数据>>请求数据有误");
            return;
        }
        synchronized(cacheName + "-" + key){
            Cache cache = cacheManager.getCache(cacheName);
            if(cache == null){
                logger.error("缓存处理SERVICE>>删除缓存数据>>发生错误：不存在缓存名称" + cacheName);
                return;
            }
            cache.evict(key);
        }
    }

    /**
     * 查询缓存数据
     * @param cacheName 缓存名称
     * @param key 缓存key
     * @param dataClass 缓存数据类
     * @param <T>
     * @return
     */
    public <T> T queryCache(String cacheName, Object key, Class<T> dataClass){
        if(StringUtils.isEmpty(cacheName) || key == null || dataClass == null){
            logger.error("缓存处理SERVICE>>查询缓存数据>>请求数据有误");
            return null;
        }
        synchronized(cacheName + "-" + key){
            Cache cache = cacheManager.getCache(cacheName);
            if(cache == null){
                logger.error("缓存处理SERVICE>>查询缓存数据>>发生错误：不存在缓存名称" + cacheName);
                return null;
            }
            T cacheData = cache.get(key, dataClass);
            return cacheData;
        }
    }

}
